﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QLab.UserControls;
using System.IO;
using System.ComponentModel.Composition;

namespace QLab.Controllers.Editor
{
	[Export]
	public class TextEditorController : TabBase
	{
		private string _text;
		private string _path;
		private string _fileName;

		private bool _modified = false;

		public TextEditorController(string Path)
			: base(new TextEditorView())
		{
			View.DataContext = this;
			_path = Path;
			FileName = System.IO.Path.GetFileName(Path);
			this.Title = FileName;

			FileInfo fi = new FileInfo(Path);
			if (fi.Exists)
			{
				Text = File.ReadAllText(Path);
			}
		}

		#region Properties

		public string FileName 
		{	
			get { return _fileName; } 
			set 
			{
				_fileName = value;
				RaisePropertyChanged("FileName");
			}
		}

		public string Text
		{
			get { return _text; }
			set 
			{	
				_text = value;
				RaisePropertyChanged("Text");
				Modified = true;
			}
		}

		public bool Modified
		{
			get { return _modified; }
			set
			{
				_modified = value;
				RaisePropertyChanged("Modified");
			}
		}

		#endregion

		#region Methods

		protected override bool CanSaveExecute()
		{
			return Modified;
		}
		protected override void Save()
		{
			try
			{
				FileStream fs = new FileStream(_path, FileMode.Create);
				StreamWriter sw = new StreamWriter(fs);
				sw.Write(Text);
				sw.Close();

				System.Windows.MessageBox.Show("Save success!");
			}
			catch (Exception e)
			{
				System.Windows.MessageBox.Show("Save failed!\n" + e.ToString());
			}
		}

		#endregion
	}
}
